(() => {
    if (window.__VTE_ALREADY_INJECTED__) return;
    window.__VTE_ALREADY_INJECTED__ = true;

    // 插入 CSS
    const style = document.createElement('link');
    style.rel = 'stylesheet';
    style.href = chrome.runtime.getURL('style.css');
    document.head.appendChild(style);

    let selectedEl = null;

    // 高亮所有可输入的区域
    const editableElements = [
        ...document.querySelectorAll('input[type="text"], textarea, [contenteditable="true"]')
    ];

    editableElements.forEach(el => {
        el.classList.add('vte-highlight');
        el.addEventListener('click', () => {
            if (selectedEl) selectedEl.classList.remove('vte-selected');
            selectedEl = el;
            el.classList.add('vte-selected');
        });
    });

    // 创建浮窗
    const overlay = document.createElement('div');
    overlay.className = 'vte-overlay';
    overlay.innerHTML = `
    <h3>模拟输入助手</h3>
    <textarea id="vte-text" placeholder="输入要模拟打字的内容..."></textarea>
    <button id="vte-submit">开始模拟输入</button>
  `;
    document.body.appendChild(overlay);

    // 模拟打字函数
    function simulateTyping(target, text, delay = 50) {
        let index = 0;

        function typeNext() {
            if (index >= text.length) return;

            const char = text[index];
            target.focus();

            // 对 contenteditable
            if (target.isContentEditable) {
                document.execCommand("insertText", false, char);
            }
            // 对 input/textarea
            else if ('value' in target) {
                const val = target.value;
                const start = target.selectionStart;
                target.value = val.slice(0, start) + char + val.slice(start);
                target.selectionStart = target.selectionEnd = start + 1;
            }

            const evt = new Event('input', { bubbles: true });
            target.dispatchEvent(evt);

            index++;
            setTimeout(typeNext, delay);
        }

        typeNext();
    }

    // 监听点击
    document.getElementById('vte-submit').onclick = () => {
        const content = document.getElementById('vte-text').value;
        if (!selectedEl) {
            alert('请先点击页面上的输入框或富文本区域');
            return;
        }
        simulateTyping(selectedEl, content);
    };
})();
